package com.example.demotest.controller;

import com.example.demotest.pojo.dto.*;
import com.example.demotest.service.IChatService;
import com.example.demotest.pojo.dto.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chats")
public class ChatController {

    private final IChatService chatService;

    @Autowired
    public ChatController(IChatService chatService) {
        this.chatService = chatService;
    }

    @PostMapping
    public ResponseEntity<ResponseMessage<ChatDto>> startChat(
            @RequestBody @Valid ChatCreateDto chatCreateDto,
            HttpServletRequest request) {
        ChatDto chatDto = chatService.startChat(chatCreateDto, request);
        return ResponseEntity.ok(
                new ResponseMessage<>(200, "聊天会话创建成功", chatDto)
        );
    }

    @PostMapping("/{chatId}/messages")
    public ResponseEntity<ResponseMessage<MessageDto>> sendMessage(
            @PathVariable Long chatId,
            @RequestBody @Valid MessageSendDto messageSendDto,
            HttpServletRequest request) {
        MessageDto messageDto = chatService.sendMessage(chatId, messageSendDto, request);
        return ResponseEntity.ok(
                new ResponseMessage<>(200, "消息发送成功", messageDto)
        );
    }

    @GetMapping("/{chatId}/messages")
    public ResponseEntity<ResponseMessage<List<MessageDto>>> getChatHistory(
            @PathVariable Long chatId) {
        List<MessageDto> messages = chatService.getChatHistory(chatId);
        return ResponseEntity.ok(
                new ResponseMessage<>(200, "聊天记录获取成功", messages)
        );
    }

    @PostMapping("/{chatId}/end")
    public ResponseEntity<ResponseMessage<Void>> endChat(
            @PathVariable Long chatId) {
        chatService.endChat(chatId);
        return ResponseEntity.ok(
                new ResponseMessage<>(200, "聊天会话已结束", null)
        );
    }

    @GetMapping("/user")
    public ResponseEntity<ResponseMessage<List<ChatDto>>> getUserChats(
            HttpServletRequest request) {
        List<ChatDto> chats = chatService.getUserChats(request);
        return ResponseEntity.ok(
                new ResponseMessage<>(200, "获取用户聊天列表成功", chats)
        );
    }
}